package migrations

import (
	"log"
	"time"

	"gorm.io/gorm"
)

func init() {
	AddMigration("metrics", func(db *gorm.DB) error {
		type Metric struct {
			ID        uint      `gorm:"primaryKey"`
			Name      string    `gorm:"size:255;not null"`
			Value     float64   `gorm:"not null"`
			Timestamp time.Time `gorm:"not null"`
		}
		return db.AutoMigrate(&Metric{})
	})
}

func CreateDbTable(db *gorm.DB) {
	// 执行所有迁移
	for name, fn := range migrations {
		// 检查表是否已经存在
		if db.Migrator().HasTable(name) {
			log.Printf("表 %v 已存在，跳过创建", name)
			continue
		}
		if err := fn(db); err != nil {
			log.Fatalf("Migration %s 失败: %v", name, err)
			break
		}
	}
}
